package com.xiaolun;

/**
 * @Author 硕鼠
 * @Date 2020/5/10 17:09
 * @Version 1.0
 * @Description 不安全的买票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"苦逼的我").start();
        new Thread(station,"帅气的你").start();
        new Thread(station,"可恶的黄牛党").start();
    }
}

class BuyTicket implements Runnable{

    private int ticket = 10;  //票
    boolean flag = true; //外部停止方式

    @Override
    public void run() {
        //买票
        while(flag){
            try {
                buy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private synchronized void buy() throws Exception {
        //判断是否有票
        if (ticket <= 0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName()+ "拿到"+ (ticket--));
    }
}